<?php
namespace Admin\Model;
use Admin\Model\BaseModel;
/**
 * @todo  订单模型
 * @since 2015-8-18
 */
class OrderModel extends BaseModel{
    
    private $cookie_time = 30;
    
    /**
     * @todo    获取订单和订单流水
     * @author  fang
     */
    public function getOrderPayment($map){
        $return = array(
            'order' => null,
            'payment' => null
        );
        if(empty($map)){
            return $return;
        }
        //退款添加活动限制 展会期间只能退当前展会下的订单(含线上订单)#线上ID第一次使用所以不用考虑时间问题
        //打算根据时间区间来判断订单
        //纸质订单退款取消限制
//         if(C('JJHH_ACTIVITY_ID') > 0){
//             $map['activity_id'] = array('in','-1,-2,-3,'.C('JJHH_ACTIVITY_ID'));
//         }
        $map['order_status'] = array('in','2,4');//2:支付成功 4:已消费
        $order = D('OrderShopView')->where($map)->select();
        if($order){
            $where['order_id'] = array('in', array_column($order, 'order_id'));
            $payment = M('order_payment')->where($where)->order('payment_id desc')->select();
            $return['order'] = $order;
            $return['payment'] = ($payment)? $payment : null ;
        }
        return $return;
    }
    
    /**
     * @todo    判断用户是否vip
     * @author  fang
     */
    public function isCustomerVip($customer_id, $activity_id){
        if($customer_id == 0 || $activity_id == 0){
            return false;
        }
        return D('Admin/ServiceActivityJoin')->getActivityJoinCustomerShow($activity_id,$customer_id);
    }
    
    /**
     * @todo    判断用户是否下过订单
     */
    public function customerOrderCount($customer_id, $activity_id, $shop_id){
        if($customer_id == 0 || $activity_id == 0){
            return false;
        }
        //当前展会下用户的有效订单数
        $where = array(
            'customer_id'  => (int)$customer_id,
            'activity_id'  => (int)$activity_id,
            'order_status' => array('gt', 1),
        );
        $order_count = M('order')->where($where)->count();
        if($order_count == 0){
            $this->error = '【对不起，首单无法使用优惠卷】';
            return false;
        }
        //当前店铺下使用优惠卷订单数
        $where['shop_id'] = (int)$shop_id;
        $where['coupons_type'] = 1;
        $shop_coupons = M('order')->field('order_id')->where($where)->find();
        if($shop_coupons){
            $this->error = '【对不起，该用户在当前店铺已使用过优惠卷】';
            return false;
        }
    }
    
    /**
     * @todo    获取订单信息
     * @author  fang
     */
    public function getOrder($map, $field = true){
        $data = D('PaperOrderView')->field($field)->where($map)->find();
        return ($data)? $data : null ;
    }
    
    /**
     * @todo    获取订单流水列表
     * @author  fang
     */
    public function getPaymentList($map){
        $list = M('order_payment')->where($map)->select();
        return ($list)? $list : null;
    }
    
    /**
     * @todo    获取补打凭证信息（流水+订单）
     */
    public function getPrintSupply($payment_id){
        if($payment_id == 0){
            return false;
        }
        //获取流水信息（订单ID，金额，操作）
        $payment_where['payment_id'] = $payment_id;
        $payment_field = 'order_id,amount,type,pay_type';
        $data = M('order_payment')->field($payment_field)->where($payment_where)->find();
        if($data == null){
            return false;
        }
        //获取订单类型
        $order_where['order_id'] = $data['order_id'];
        $order_type = M('order')->where($order_where)->getField('order_type');
        $data['order_type'] = (int)$order_type;
        return $data;
    }
    
    /**
     * @todo    获取打印信息
     */
    public function getPrintInfoNew(){

        $order_id = (int)I('order_id', 0);
        $payment_id = (int)I('payment_id', 0);
        if($order_id == 0){
            $this->error = 'order_id参数错误';
            return false;
        }
        $where['order_id'] = $order_id;
        $order = D('OrderShopView')->where($where)->find();
        if(empty($order)){
            $this->error = '无效订单ID：'.$order_id;
            return false;
        }
        $order['customer_name'] = getCustomerNameNew($order['customer_id']);
        //获取商户信息
        if((int)$order['merchant_id'] > 0){
            $merchant = M('merchant')->field('merchant_address,merchant_phone,merchant_fixed_phone')->where(array('merchant_id' => (int)$order['merchant_id']))->find();
            $order['merchant_address'] = ($merchant)? $merchant['merchant_address'] : '' ;
            $order['merchant_phone'] = ($merchant)? $merchant['merchant_phone'] : '' ;
            $order['merchant_fixed_phone'] = ($merchant)? $merchant['merchant_fixed_phone'] : '' ;
            
        }
        //备注信息调用（商品名称，介绍，现价格，原价格等）
	    $data = json_decode($order['remark'],true);
	    $order['goods'] = ($data['info']['goods'])? $data['info']['goods'] : '' ;
	    $order['title'] = ($data['info']['title'])? $data['info']['title'] : '' ;
	    $order['price'] = ($data['info']['price'])? $data['info']['price'] : '' ;
	    $order['saleprice'] = ($data['info']['saleprice'])? $data['info']['saleprice'] : '' ;
	    //流水
        if($payment_id > 0){
            $where['payment_id'] = $payment_id;
            $payment = M('order_payment')->field('payment_id,amount,pay_type')->where($where)->find();
            return ($payment)? array_merge($order,$payment) : $order ;
        }else {
            return $order; 
        }
        
    }
    
    /**
     * @todo    生成订单模型
     * @author  fang
     */
    public function pay(){
        
        $shop_id = (int)I('shop_id', 0);
        $customer_id = (int)I('customer_id', 0);
        $paper_order = strip_tags(I('order_number',''));
        $amount = (float)I('amount', 0);
        $pay_type = (int)I('pay_type', 0);
        $activity_id = (int)I('activity_id', 0);
        $type = (int)I('type', 0);
        //1203 update start
        $coupons_type = (int)I('coupons_type', 0);
        $coupons_amount = (float)I('coupons_amount', 0);
        //1203 update end
        if($activity_id == 0){
            $this->error = '【请选择活动】';
            return false;
        }
        if($customer_id == 0){
            $this->error = '【请扫描客户二维码】或【输入客户手机号并回车】';
            return false;
        }
        if($shop_id == 0){
            $this->error = '【请扫描纸质订单】或【输入纸质订单号并回车】';
            return false;
        }
        if(empty($paper_order)){
            $this->error = '【请扫描纸质订单】或【输入纸质订单号并回车】';
            return false;
        }
        if($amount <= 0){
            $this->error = '【请输入实收金额】';
            return false;
        }
        if($pay_type == 0){
            $this->error = '【请勾选支付方式】';
            return false;
        }
        //优惠卷判断(vip)
        if($coupons_type > 0 && $coupons_amount > 0){
            //使用优惠卷订单金额大于等于100
            if($amount < 80){
                $this->error = '【对不起，优惠卷适用于100元以上的订单】';
                return false;
            }
            //判断用户在当前活动下的票别类型
            $is_vip = $this->isCustomerVip($customer_id, $activity_id);
            if($is_vip != 1){
                $this->error = '【对不起，只有vip客户才可以使用优惠卷】';
                return false;
            }
            //当前展会下用户的有效订单数
            $where = array(
                'customer_id'  => (int)$customer_id,
                'activity_id'  => (int)$activity_id,
                'order_status' => array('gt', 1),
            );
            $order_count = M('order')->where($where)->count();
            if($order_count == 0){
                $this->error = '【对不起，首单无法使用优惠卷】';
                return false;
            }
            //当前店铺下使用优惠卷订单数
            $where['shop_id'] = (int)$shop_id;
            $where['coupons_type'] = 1;
            $shop_coupons = M('order')->field('order_id')->where($where)->find();
            if($shop_coupons){
                $this->error = '【对不起，该用户在当前店铺已使用过优惠卷】';
                return false;
            }
        }
        
        //订单是否存在
        $field = 'order_id,order_amount,order_pay_amount,coupons_type,coupons_amount,order_status';
        $order = M('order')->field($field)->where(array('paper_order' => $paper_order, 'order_type' => 1))->find();
        if($order){
            if((int)$order['order_status'] < 0 || (int)$order['order_status'] > 2){
                $this->error = '【只能对未支付和已支付订单进行支付】';
                return false;
            }
            if((int)$order['coupons_type'] > 0 && $coupons_type > 0){
                $this->error = '【该订单已使用过优惠券】';
                return false;
            }
            //返回订单ID
            if($type == 0){
                //检查是否重复支付
                if(cookie('jjhh_order_id_'.$order['order_id']) > 0){
                    $this->error = '【请不要对同订单进行重复支付，再支付请等待30s】';
                    return false;
                }
                return $order['order_id'];
            }
            //已有订单再支付type=1
            $data = array(
                'order_amount' => $amount,
                'pay_type' => $pay_type,
                'coupons_type' => $coupons_type,    //1203 update 
                'coupons_amount' => $coupons_amount,//1203 update 
            );
            $order_save = $this->orderPay($order, $data);
            return ($order_save)? $order['order_id'] : false ;
        }
        //识别码
        try{
            //生成订单
            $order_data = array(
                'shop_id' => $shop_id,
                'activity_id' => $activity_id,
                'customer_id' => $customer_id,
                'paper_order' => $paper_order,
                'order_amount' => 0,
                'order_pay_amount' => 0,
                'order_type' => 1,                  //1:线下订单;2:线上订单;
                'order_status' => 0,
                'coupons_type' => 0,                //是否使用优惠券：1203 update 
                'coupons_amount' => 0,              //优惠券金额：1203 update
                'remark' => '',
                'check_code' => mt_rand(100000,999999),
                'create_time' => NOW_TIME
            );
            $order_add = M('order')->add($order_data);
            if($order_add === false){
                $this->error = '服务器繁忙，请稍后再试';
                return false;
            }
            //日志记录
            $this->orderLogAdd($order_add);
            return $order_add;
        }catch (\Exception $e){
            $this->error = $e->getMessage();
            return false;
        }
    }
    
    /**
     * @todo    已生成订单支付
     * @param   $data{ amount, pay_type, coupons_type, coupons_amount }
     * @author  fang
     */
    public function orderPay($order, $data){
        if(empty($order) || empty($data)){
            return false;
        }
        $order_id = (int)$order['order_id'];
        
        try{
            $this->startTrans();
            //订单金额和状态修改
            $save_data['order_amount'] = $order['order_amount'] + $data['order_amount'];
            $save_data['order_pay_amount'] = $order['order_pay_amount'] + $data['order_amount'];
            $save_data['order_status'] = 2;//2：已付款 
            //优惠卷处理 1203
            if($data['coupons_type'] > 0){
                $save_data['coupons_type'] = $data['coupons_type'];
                $save_data['coupons_amount'] = $data['coupons_amount'];
                //优惠卷相关金额修改
                $save_data['order_amount'] += $data['coupons_amount'];
                $save_data['order_pay_amount'] += $data['coupons_amount'];
            }
            $order_save = M('order')->where(array('order_id' => $order_id))->save($save_data);
            //流水记录
            $payment_add = $this->orderPaymentAdd($order_id, $data['order_amount'], $data['pay_type'], 1);//payment 1:支付
            //优惠卷流水 1203
            $coupons_payment_add = true;
            if($data['coupons_type'] > 0){
                $coupons_payment_add = $this->orderPaymentAdd($order_id, $data['coupons_amount'], 9, 1);//优惠卷支付类型9
            }
            if($order_save !== false && $payment_add !== false && $coupons_payment_add !== false){
                $this->commit();
                //正常流水日志
                $log_add = $this->orderLogAdd($order_id, $data['order_amount'], $data['pay_type'], 2);  //log 2:付款成功
                //优惠卷流水日志
                if($data['coupons_type'] > 0){
                    $log_add = $this->orderLogAdd($order_id, $data['coupons_amount'], 9, 2);                //log 2:付款成功
                }
                //支付订单成功
                cookie('jjhh_order_id_'.$order_id, $order_id, $this->cookie_time);
                return true;
            }else{
                $this->rollback();
                $this->error = '流水：'.$payment_add.' 订单：'.$order_id.' 日志：'.$log_add.' 金额：'.$data['order_amount'];
                return false;
            }
        }catch (\Exception $e){
            $this->error = $e->getMessage();
            return false;
        }
        
    }
    
    /**
     * @todo    退款模型
     * @author  fang
     */
    public function refund(){
        $payment_id = (int)I('payment_id', 0);
        $order_id = (int)I('order_id', 0);
        if($order_id ==0 || $payment_id==0){
        	$this->error = 'order_id或payment_id参数有误';
        	return false;
        }
        $payment_where['payment_id'] = $payment_id;
        $payment_where['order_id'] = $order_id;
        $payment = M('order_payment')->field('order_id,amount,pay_type,type')->where($payment_where)->find();
        if(!$payment || (int)$payment['type'] == 2){
            $this->error = '无效付款信息或该支付已退款';
            return false;
        }
        
        try {
            $this->startTrans();
            //标记此笔流水退款
            $refund_data = array(
                'type' => 2,
                'refund_id' => UID
            );
            $payment_result = M('order_payment')->where($payment_where)->save($refund_data);//2:退款
            $order_where['order_id'] = $payment_where['order_id'];
            //查询订单总金额
            $order= M('order')->field('order_amount,order_type')->where($order_where)->find();
            //增加订单退款金额
            $order_refund_amount = M('order')->where($order_where)->setInc('order_refund_amount', $payment['amount']);
            //计算订单剩余金额
            $amount = $order['order_amount'] - $payment['amount'];
            //订单状态类型
            $log_type = 3;
            if($amount == 0){
                $order_data['order_status'] = $log_type;
            }
            $order_data['order_amount'] = $amount;
            $amount_result = ($amount < 0 || $order_refund_amount === false)? false : true ;
            //修改订单信息
            $order_result = M('order')->where($order_where)->setField($order_data);
            $log_add = $this->orderLogAdd($payment['order_id'], $payment['amount'], $payment['pay_type'], $log_type);
            if($payment_result !== false && $order_result !== false && $log_add !== false && $amount_result !== false){
                $this->commit();
                return true;
            }else{
                $this->rollback();
                $this->error = '流水：'.$payment_result.' 订单：'.$order_result.' 日志：'.$log_add.' 总金额：'.$amount_result;
                return false;
            }
        }catch (\Exception $e){
            $this->error = $e->getMessage();
            return false;
        }
    }
    
    /**
     * @todo    获取操作人员
     */
    public function getUserList(){
        $where['status'] = 1;
        return M('member')->field('uid,login_name')->where($where)->select();
    }
    
    /**
     * @todo    获取流水总和
     * @param   $map
     */
    public function getAmountSum($map){
        return D('OrderPaymentView')->where($map)->sum('amount');
    }
    
    /**
     * @todo    订单状态修改（申请核销，返款，申请退款）
     * @param   id  
     * @param   status
     * @author  fang
     */
    public function orderStatus($id, $type){
        if(empty($id)){
            $this->error = '请选择操作数据';
            return false;
        }
        $where['order_id'] = array('in', $id);
        
        try {
            $this->startTrans();
            $save_data['order_status'] = $type;
            //返款操作记录返款时间
            if($type == 7){//返款时间
                $save_data['back_time'] = NOW_TIME;
            }
            $result = M('order')->where($where)->save($save_data);
            $order = M('order')->field('order_id,order_amount')->where($where)->select();
            $data = array();
            $count = count($order);
            for ($i = 0; $i < $count; $i++){
                $data[$i]['order_id'] = $order[$i]['order_id'];
                $data[$i]['uid'] = UID;
                $data[$i]['money'] = $order[$i]['order_amount'];
                $data[$i]['pay_type'] = 0;
                $data[$i]['log_type'] = $type;
                $data[$i]['create_time'] = NOW_TIME;
            }
            $log_add = M('order_log')->addAll($data);
            if($result !== false && $log_add !== false){
                $this->commit();
                return true;
            }else{
                $this->rollback();
                return false;
            }
        }catch (\Exception $e){
            $this->error ='修改状态失败';
            return false;
        }
    }
    
    /**
     * @todo    订单状态修改（驳回）
     * @param   id
     * @author  fang
     */
    public function orderStatusReject($id){
        if(empty($id)){
            $this->error = '请选择操作数据';
            return false;
        }
        $where['order_id'] = array('in', $id);
        $order = M('order')->field('order_type,order_status')->where($where)->find();
        if($order['order_status'] != 5 || $order['order_type'] == 0){
            $this->error = '该订单处于无法驳回状态：'.(int)$order['order_status'].(int)$order['order_status'];
            return false;
        }
        $type = ($order['order_type'] == 1)? 2 : 4 ;//1:线下订单;2:线上订单;
        $result = M('order')->where($where)->setField('order_status', $type);
        if($result === false){
            $this->error = '驳回申请失败';
            return false;
        }
        $this->orderLogAdd($id,0,0,10);//10:驳回操作
        return true;
    }
    
    /**
     * @todo    订单日志（写入）
     * @param   int $order_id
     * @param   float $amount
     * @param   int $pay_type
     * @param   int $log_type
     * @return  boolean
     * @author  fang
     */
    public static function orderLogAdd($order_id, $amount = 0, $pay_type = 0, $log_type = 0){
        if(empty($order_id)){
            return false;
        }
        $log_data = array();
        $log_data['order_id'] = $order_id;
        $log_data['uid'] = UID;
        $log_data['money'] = $amount;
        $log_data['pay_type'] = $pay_type;
        $log_data['log_type'] = $log_type;
        $log_data['create_time'] = NOW_TIME;
        return M('order_log')->add($log_data);
    }
    
    /**
     * @todo    订单流水（写入）
     * @param   int $order_id
     * @param   float $amount
     * @param   int $pay_type
     * @param   int $type
     * @return  boolean
     * @author  fang
     */
    public static function orderPaymentAdd($order_id,$amount,$pay_type,$type){
        if(empty($order_id) || empty($amount) || empty($type)){
            return false;
        }
        $payment_data = array();
        $payment_data['order_id'] = $order_id;
        $payment_data['amount'] = $amount;
        $payment_data['pay_type'] = $pay_type;
        $payment_data['type'] = $type;
        $payment_data['create_time'] = NOW_TIME;
        $payment_data['collect_id'] = UID;
        $payment_data['refund_id'] = 0;
        return M('order_payment')->add($payment_data);
    }

    /**
     * @todo 生成纸质订单
     * @param int activity_id 活动id
     * @param int shop_id 店铺id
     * @param int order_start_num 订单开始编号
     * @param int order_end_num 订单开始编号
     * @author PHP@妖孽 <dino_ma@163.com>
     */
    public function build(){
    	$activity_id = (int)I('activity_id');
    	$shop_id = (int)I('shop_id');
    	$order_start_num = (int)I('order_start_num');
    	$order_end_num = (int)I('order_end_num');
    	if($order_start_num ==0 || $order_end_num == 0){
    		$this->error='订单起止参数有误';
    		return false;
    	}
    	if($order_end_num<$order_start_num){
    		$this->error='结束订单必须大于开始订单';
    		return false;
    	}
    	if(($order_end_num-$order_start_num)>200){
    	    $this->error='单次订单不能卖大于200张';
    	    return false;
    	}
    	$shop_is = D('Admin/ShopActivity')->shopIsInActivity($activity_id,$shop_id);
    	if(empty($shop_is)){
    		$this->error='当前店铺不在活动下';
    		return false;
    	}
    	$data = array();//初始化写入数据
    	$k=0;
    	if($order_start_num == $order_end_num){
    	    $data[$k]['paper_order_num']=$order_start_num;
    	    $data[$k]['activity_id']=$activity_id;
    	    $data[$k]['shop_id']=$shop_id;
    	    $data[$k]['sell_uid']=UID;
    	    $data[$k]['status']=1;
    	    $data[$k]['order_type']=0;
    	    $data[$k]['create_time']=NOW_TIME;
    	    $data[$k]['update_time']=NOW_TIME;
    	}else{
        	for ($i=$order_start_num;$i<=$order_end_num;$i++){
        		$data[$k]['paper_order_num']=$i;
        		$data[$k]['activity_id']=$activity_id;
        		$data[$k]['shop_id']=$shop_id;
        		$data[$k]['sell_uid']=UID;
        		$data[$k]['status']=1;
        		$data[$k]['order_type']=0;
        		$data[$k]['create_time']=NOW_TIME;
        		$data[$k]['update_time']=NOW_TIME;
        		$k++;
        	}
    	}
    	try{
    		$obj =M('PaperOrder');
    		$obj->startTrans();
    		$add = $obj->addAll($data);
    		if($add === false){
    		    $obj->rollback();
    		    $this->error= '订单号有重复';
    		    return false;
    		}else{
    		    $obj->commit();
    		    return true;
    		}
    	}catch (\Exception $e){
            $this->error = '订单号有重复或系统繁忙';
            return false;
        }
    }
    
    /**
     * @todo    线上订单绑定线下纸质订单（新）
     * @param   int     type            查询／绑定
     * @param   int     order_id        线上订单id
     * @param   int     paper_order     纸质订单号
     * @param   int     activity_id     展会id
     * @author  fang
     */
    public function paperOrderSaleBind(){
        $type = (int)I('type', 0);
        $paper_order_num = (int)I('paper_order');
        $order_id = (int)I('order_id');
        $activity_id = (int)I('bind_activity_id');//C('JJHH_ACTIVITY_ID');
        //临时修改
        if($activity_id == 0){
            $this->error = '请选择绑定活动';
            return false;
        }
        if($paper_order_num == 0){
            $this->error = '请输入纸质订单号';
            return false;
        }
        if($order_id == 0){
            $this->error = '请选择绑定的线上订单';
            return false;
        }
        //线上订单详细
        $field = 'order_id,shop_id,goods_id,customer_id,order_status,paper_order';
        $where['order_id'] = $order_id;
        $where['order_type'] = 2;
        $order_info = M('order')->field($field)->where($where)->find();
        //订单状态判断
        if(!$order_info){
            $this->error = '线上订单不存在';
            return false;
        }
        if($order_info['order_status'] != 2){
            $this->error = '线上订单未支付成功或已绑定';
            return false;
        
        }
        //纸质订单判断
        $paper_where = array(
            'paper_order_num' => $paper_order_num,
            'status' => 1
        );
        $paper_order_info = M('paper_order')->where($paper_where)->getField('shop_id');
        if($paper_order_info){
            $this->error = '纸质订单已被绑定';
            return false;
        }

        //判断线上订单与纸质订单
        if($type == 1){
            return true;
        }
        $shop_id = (int)$order_info['shop_id'];
        
        try {
            $this->startTrans();
            //自动销售纸质订单
            $paper_data = array(
                'paper_order_num' => $paper_order_num,
                'activity_id' => $activity_id,
                'shop_id' => $shop_id,
                'sell_uid' => UID,
                'status' => 1,
                'order_type' => 1,
                'create_time' => NOW_TIME,
                'update_time' => NOW_TIME,
            );
            if(false === M('paper_order')->add($paper_data)){
                $this->rollback();
                $this->error = '纸质订单自动销售失败';
                return false;
            }
            //纸质订单写入订单
            $order_data = array(
                'shop_id' => $shop_id,
                'goods_id' => (int)$order_info['goods_id'],
                'customer_id' => (int)$order_info['customer_id'],
                'activity_id' => $activity_id,
                'paper_order' => $paper_order_num,
                'order_status' => 0,
                'order_amount' => 0,
                'order_pay_amount' => 0,
                'order_refund_amount' => 0,
                'order_type' => 1,
                'create_time' => NOW_TIME,
                'check_code' => mt_rand(100000, 999999)
            );
            $new_order_id = M('order')->add($order_data);
            if(false === $new_order_id){
                $this->rollback();
                $this->error = '纸质订单写入订单失败';
                return false;
            }
            //修改线上订单状态
            $online_data = array(
                'order_status' => 4,
                'paper_order' => $paper_order_num
            );
            if(false === $this->where($where)->save($online_data)){
                $this->rollback();
                $this->error = '线上订单消费失败';
                return false;
            }
            $this->commit();
            //消费订单日志
            $this->orderLogAdd($order_id, 0, 8, 4);
            //生成订单日志
            $this->orderLogAdd($new_order_id);
            //绑定订单日志
            $this->orderLogAdd($new_order_id, 0, 8, 8);
            return true;
        }catch (\Exception $e){
            $this->error ='请输入空的纸质订单';
            return false;
        }
    }
    
    
    
    /**
     * @todo 纸质订单绑定线上订单
     * @param order_id int 线上订单
     * @param paper_order int 线下订单
     * @author  PHP@妖孽<dino_ma@163.com>
     */
	public function paperOrderBindingOrder($order_id=0,$paper_order=0){
		$order_id = (int)$order_id;
		$paper_order = (int)$paper_order;
		if($order_id ==0 || $paper_order ==0){
			$this->error='参数有误.~';
			return false;
		}
		// 先查纸质订单存不存在
		$paper_order_map = array('paper_order_num'=>$paper_order,'order_type'=>0,'status'=>1);
		$paper_obj = M('PaperOrder');
		$paper_order_info = $paper_obj->field('paper_order_num,shop_id,activity_id')->where($paper_order_map)->find();
		if(empty($paper_order_info)){
			$this->error ='纸质订单不存在或已被绑定~';
			return false;
		}
		//查看线上订单是否绑定过 纸质订单 如果绑定过 则跳出
		$order_map = array('order_id'=>$order_id,'order_type'=>2,'order_status'=>2,'paper_order'=>0);
		$order_info = $this->field('activity_id,order_amount,customer_id,remark')->where($order_map)->find();
		if(empty($order_info)){
			$this->error = '此线上订单未支付成功或已绑定~';
			return false;
		}
		
		if($order_info['activity_id'] != $paper_order_info['activity_id']){
			$this->error = '纸质订单与线上订单活动不符~';
			return false;
		}
		
		try {
			$this->startTrans();
			//如果没绑定过 则修改纸质订单状态 绑定线上订单
			if(false === $paper_obj->where($paper_order_map)->save(array('order_type'=>1))){
				$this->rollback();
				$this->error = '纸质订单状态修改失败';
				return false;
			}
			//绑定消费订单
			if(false === $this->where($order_map)->save(array('order_status'=>4,'paper_order'=>$paper_order))){
				$this->rollback();
				$this->error = '线上订单消费失败';
				return false;
			}else {
				//绑定消费当前订单
				$this->orderLogAdd($order_id,0,8,4);
		//		$this->orderPaymentAdd($order_id,$order_info['order_amount'],8,1);
			}
			//生成一个新订单
			$order_data = array('shop_id'=>$paper_order_info['shop_id'],'customer_id'=>$order_info['customer_id'],'activity_id'=>$order_info['activity_id'],'paper_order'=>$paper_order,'order_status'=>0,'order_amount'=>0,'order_pay_amount'=>0,'order_refund_amount'=>0,'order_type'=>1,'remark'=>$order_info['remark'],'create_time'=>NOW_TIME,'check_code' => mt_rand(100000, 999999));
			$new_order_id= $this->add($order_data);
			if(!$new_order_id){
				$this->rollback();
				$this->error = '生成线上订单失败';
				return false;
			}else{
				//绑定消费当前订单
				//pay_type 只有支付成功才会有 .~
				$this->orderLogAdd($new_order_id);
				$this->orderLogAdd($new_order_id,0,8,8);
// 				$this->orderPaymentAdd($new_order_id,$order_info['order_amount'],8,1);
			}
			$this->commit();
			return true;
		}catch (\Exception $e){
            $this->error ='纸质订单绑定失败';
            return false;
        }
	}
	
	/**
	 * @todo 订单详情（OrderShopView视图）（线上）
	 * @param int $order_id
	 * @author sap
	 */
	public function orderShopShow($order_id=0,$map=array()){
		$order_id = (int)$order_id;
		if($order_id == 0){
			$this->error = '请正确操作';
			return false;
		}
		$where = array();//初始化查询条件
		$where['order_id'] = $order_id;
		//查询条件
		if(empty($map)){
			$map =$where;
		}else{
			$map = array_merge($where,$map);
		}
		$order = D('Admin/OrderShopView')->where($map)->find();
		//获取商户信息
		if((int)$order['merchant_id'] > 0){
		    $merchant = M('merchant')->field('merchant_address,merchant_phone,merchant_fixed_phone')->where(array('merchant_id' => (int)$order['merchant_id']))->find();
		    $order['merchant_address'] = ($merchant)? $merchant['merchant_address'] : '' ;
		    $order['merchant_phone'] = ($merchant)? $merchant['merchant_phone'] : '' ;
		    $order['merchant_fixed_phone'] = ($merchant)? $merchant['merchant_fixed_phone'] : '' ;
		}
		//获取用户姓名
		$order['customer_name'] = getCustomerNameNew($order['customer_id']);
		//备注信息调用（商品名称，介绍，现价格，原价格等）
	    $data = json_decode(urldecode($order['remark']),true);
	    $order['tid'] = ($data['info']['tid'])? $data['info']['tid'] : '' ;
	    $order['goods'] = ($data['info']['goods'])? $data['info']['goods'] : '' ;
	    $order['title'] = ($data['info']['title'])? $data['info']['title'] : '' ;
	    $order['price'] = ($data['info']['price'])? number_format($data['info']['price'], 2) : '' ;
	    $order['saleprice'] = ($data['info']['saleprice'])? number_format($data['info']['saleprice'], 2) : '' ;
	    //线上流水
	    if($order['order_type'] == 2){
	        $where_order['order_id'] = $order_id;
	        $where_order['type'] = 1;
	        $payment = M('order_payment')->field('pay_type')->where($where_order)->find();
	        return ($payment)? array_merge($order,$payment) : $order ;
	    }else{
	        return $order;
	    }
	}
	
	/**
	 * @todo 获取商品订单快照信息
	 * @param int $order_id
	 * @param string $field
	 */
	public function getOrderSnap($order_id, $field = true){
	    if(empty($order_id)){
	        $this->error = '参数错误';
	        return null;
	    }
	    if(is_array($order_id)){
	        $where['order_id'] = array('in', $order_id);
	        return M('order_goods_snapshot')->field($field)->where($where)->select();
	    }else{
	        $where['order_id'] = (int)$order_id;
	        return M('order_goods_snapshot')->field($field)->where($where)->find();
	    }
	}
	
	/**
	 * @todo 订单日志列表
	 * @param array $where 查询条件数组
     * @param string $field 查询字段
     * @param string $orderby 排序
     * @return false|array 列表数组
	 * @author sap
	 */
	public function orderLogList($map = array(),$field= '',$orderby='log_id asc'){
		return M('order_log')->where($map)->field($field)->order($orderby)->select();
	}
	

	/*----------------------- 订单换礼-方法 -----------------------*/
	
	/**
	 * @todo 订单-店铺信息-列表
	 * @author sap
	 * @since 2016-2-18
	 */
    public function getOrderShop($map, $field = true){
        $data = D('OrderShopView')->where($map)->field($field)->find();
        return ($data)? $data : null ;
    }
    
    /**
     * @todo 订单换礼
     * @author sap
     * @since 2016-2-18
     */
    public function addOrderGift(){
        $present_id = (int)I('present_id');
        $activity_id = (int)I('activity_id');
        $paper_order = strip_tags(I('paper_order'), '');
        $gift_num = (int)I('gift_num');
        if(empty($paper_order) ) {
            $this->error = '【请扫描纸质订单】或【输入纸质订单号并回车】';
            return false;
        }
        if($activity_id == 0){
            $this->error = '【请选择活动】';
            return false;
        }
        if($present_id == 0){
            $this->error = '【请选择礼品】';
            return false;
        }
        if($gift_num == 0){
            $this->error = '【请填写礼品数量】';
            return false;
        }
        //查看订单信息
        $order_shop_info = $this->getOrderShop(array('activity_id'=>$activity_id,'paper_order'=>$paper_order),'order_id,customer_id,paper_order,order_amount,conf_category_id');
        if(empty($order_shop_info)){
            $this->error = '无订单信息';
            return false;
        }
        //判断订单金额
        if((int)$order_shop_info['order_amount'] == 0){
            $this->error = '当前订单金额不可以换礼';
            return false;
        }
        //判断在该品类下是否已经换过礼
        $map = array();
        $map['activity_id'] = $activity_id;
        $map['customer_id'] = $order_shop_info['customer_id'];
        $map['category_id'] = $order_shop_info['conf_category_id'];
        $order_gift_paper_info = D('OrderGiftPaperView')->where($map)->field('paper_order')->select();
        if(!empty($order_gift_paper_info)){
            $this->error = '在该品类下已换礼';
            return false;
        }
        //添加iweb_order_gift表中的数据
        $data = array();
        $data['present_id'] = $present_id;
        $data['customer_id'] = $order_shop_info['customer_id'];
        $data['activity_id'] = $activity_id;
        $data['gift_num'] = $gift_num;
        $data['change_time'] = NOW_TIME;
        $data['status'] = 0;
        $data['uid'] = UID;
        M()->startTrans();
        $gift_id = M('OrderGift')->add($data);
        if(empty($gift_id)){
            M()->rollback();
            $this->error = '换礼失败，请重试';
            return false;
        }
        //添加iweb_order_gift_paper表中的数据
        $data_gift_paper = array();
        $data_gift_paper['gift_id'] = $gift_id;
        $data_gift_paper['paper_order'] = $order_shop_info['paper_order'];
        $data_gift_paper['order_id'] = $order_shop_info['order_id'];
        $data_gift_paper['category_id'] = $order_shop_info['conf_category_id'];
        $suess_num = M('OrderGiftPaper')->add($data_gift_paper);
        if(empty($suess_num)){
            M()->rollback();
            $this->error = '换礼失败';
            return false;
        }
        M()->commit();
        return true;
    }
    
    /**
     * @todo 根据礼品记录表主键归还礼品
     * @author sap
     * @since 2016-2-19
     */
    public function delOrderGift(){
        $gift_id = (int)I('gift_id');
        if($gift_id == 0){
            $this->error = '礼品ID丢失';
            return false;
        }
        $map = array();
        $map['gift_id'] = $gift_id;
        $data['back_time'] = NOW_TIME;
        $data['status'] = 1;
        $data['uid'] = UID;
        M()->startTrans();
        if(M('OrderGift')->where($map)->save($data) === false){
            M()->rollback();
            $this->error = '换礼记录删除失败';
            return false;
        }
        if(M('OrderGiftPaper')->where($map)->delete() === false){
            M()->rollback();
            $this->error = '纸质订单换礼记录删除失败';
            return false;
        }
        M()->commit();
        return true;
    }
    
    /**
     * @todo 根据纸质订单查询换礼记录
     * @author sap
     * @since 2016-2-19
     */
    public function getOrderGift(){
        $paper_order = (int)strip_tags(I('order_number', '0'));
        if($paper_order == 0){
            $this->error = '请扫描或输入纸质订单';
            return false;
        }
        $obj_order_gift_paper = M('OrderGiftPaper');
        $gift_id = $obj_order_gift_paper->where(array('paper_order'=>$paper_order))->getField('gift_id');//根据纸质订单号查询换礼记录Id
        if(empty($gift_id)){
            $this->error = '该纸质订单还没有换礼';
            return false;
        }
        $gift_info = M('OrderGift')->where(array('gift_id'=>$gift_id,'status'=>'0'))->find();//根据换礼记录ID，查询换礼信息详情
        if(empty($gift_info)){
            $this->error = '该纸质订单还没有换礼';
            return false;
        }
        $gift_info['activity_name'] = getActivityName($gift_info['activity_id']);
        $gift_info['customer_phone'] = getCustomerName($gift_info['customer_id']);
        $gift_info['present_name'] = getPresentTitle($gift_info['present_id'],$gift_info['activity_id']);
        $gift_info['member_name'] = getUserName($gift_info['uid']);
        $gift_info['change_time'] = time_format($gift_info['change_time']);
        $gift_order_list = $obj_order_gift_paper->where(array('gift_id'=>$gift_id))->select();//根据换礼记录ID，查询本条记录下所有纸质订单号
        if(empty($gift_order_list)){
            $this->error = '该纸质订单还没有换礼';
            return false;
        }
        foreach ($gift_order_list as $key=>$val){
            $gift_order_list[$key]['category_name'] = getConfCategoryName($val['category_id']);
        }
        $result = array();
        $result['gift_info'] = $gift_info;//详情
        $result['gift_order_list'] = $gift_order_list;//换礼下纸质订单号
        return $result;
    }
    
    /**
     * @todo    查看纸质订单是否换礼
     */
    public function isOrderGift($paper_order){
        if(empty($paper_order)) return false;
        $info = M('order_gift_paper')->field('gift_id')->where(array('paper_order' => $paper_order))->find();
        return ($info)? true : false ;
    }
    
    /**
     * @todo    质检店铺列表
     * @author  fang
     */
    public function getCheckShop(){
        $activity_id = (int)I('activity_id');
        if($activity_id == 0){
            return null;
        }
        $map = array();
        $map['activity_id'] = $activity_id;
        $map['order_status'] = 5;   // 申请核销
        $apply_start_time = (I('apply_start_time'))? strtotime(I('apply_start_time')) : 0 ;
        $apply_end_time = (I('apply_end_time'))? strtotime(I('apply_end_time')) : NOW_TIME ;
        if($apply_start_time > 0){
            $map['apply_time'] = array('between', array($apply_start_time, $apply_end_time));
        }
        
        $order_list = D('CheckOrderView')->where($map)->select();
        $data = array();
        foreach ($order_list as $key=>$val){
            if($val['member_id'] > 0 && $val['is_pass'] == 0){
                if(!isset($data[$val['shop_id']])){
                    $data[$val['shop_id']] = array(
                        'activity_id' => $val['activity_id'],
                        'merchant_id' => $val['merchant_id'],
                        'shop_id' => $val['shop_id'],
                        'order_status' => $val['order_status'],
                    );
                }
                $data[$val['shop_id']]['order_count'] += 1;
                $data[$val['shop_id']]['_order'][] = $val['paper_order'];
            }
        }
        return $data;
    }
    
}
